<template>
  <div id="barChart" ref="echarts" style="width: 100%;height:100%; margin: auto;" />
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    chartData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {}
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    // this.$nextTick(() => {
    this.initChart()
    // });
  },
  methods: {
    initChart() {
      let myChart = echarts.getInstanceByDom(document.getElementById('barChart'))
      if (myChart == null) {
        myChart = echarts.init(this.$refs.echarts)
      }
      // var myChart = echarts.init(this.$refs.echarts);
      // window.addEventListener('resize', function() {
      //   that.myChart.resize()
      // })
      var option = {
        title: {
          text: this.chartData.chartTitle,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xData,
          axisLine: { show: true },
          axisTick: { show: true },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          axisLine: { show: true },
          axisTick: { show: true },
          splitLine: { show: false },
          axisLabel: { show: true }
        },
        series: [
          {
            type: 'bar',
            data: this.chartData.yData,
            barWidth: 15,
            itemStyle: {
              borderRadius: 10,
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#37BBF8' },
                { offset: 1, color: '#3977E6' }
              ])
            }
          }
        ]
      }
      myChart.setOption(option, true)
    },
    beforeDestroy() {
      // 在组件生命周期结束的时候销毁，removeEventListener和addEventListener中对应的参数要一致。
      window.removeEventListener('resize', function() {
        this.myChart.resize()
      })
    }
  }
}
</script>

<style></style>

